package myLearnjdk.jdk.util.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 并发
 * @author BriansPC
 *
 */
public class Concurent {
	
	public static void main(String[] args) {
//		futureTask();
		threadPoolExecutorTest();
	}
	
	/**
	 * FutureTask练习
	 */
	public static void futureTask(){
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		FutureTask<Object> f = new FutureTask<Object>(new Runnable() {
			
			@Override
			public void run() {
				int i=10;
				while(i>0){
					try {
						i--;
						System.out.println("线程执行一次i="+i);
					
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						/**
						 * 通过捕获InterruptedException异常 停止线程运行
						 */
						e.printStackTrace();
						System.out.println("线程停止运行");
						break;
					}
				}
				
			}
		}, "true");
		executorService.execute(f);
		System.out.println("。。。。。");
		f.cancel(false);//当参数置为“true”会让指定FutureTask抛出InterruptedException异常
		
	}
	
	
	/**
	 * 自定义线程池的命名
	 */
	public static void threadPoolExecutorTest(){
//		private static final ThreadFactory sThreadFactory = new ThreadFactory() {
//		private final AtomicInteger mCount = new AtomicInteger(1);
//
//		    public Thread newThread(Runnable r) {
//		        return new Thread(r, "我的线程 #" + mCount.getAndIncrement());
//		    }
//		};
		
		ThreadFactory myFactory = new ThreadFactory() {
			AtomicInteger index = new AtomicInteger(0);
			@Override
			public Thread newThread(Runnable r) {
				// TODO Auto-generated method stub
				return new Thread(r,"我的线程"+index.addAndGet(1));
			}
		};
		
		ThreadPoolExecutor executor = new ThreadPoolExecutor(6, 20, 120, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), myFactory);

		executor.execute(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("当前线程名称:"+Thread.currentThread().getName());
				
			}
		});
		executor.execute(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("当前线程名称:"+Thread.currentThread().getName());
				
			}
		});
		executor.execute(new Runnable() {
			
			@Override
			public void run() {
				System.out.println("当前线程名称:"+Thread.currentThread().getName());
				
			}
		});
	}

}
